<template>
  <div class="filter">
    <div class="uploadBtn">
      <el-date-picker
        v-model="dateStartTime"
        type="date"
        size="large"
        :disabled-date="disabledDate1"
      />
    </div>
    <div class="uploadBtn" style="line-height: 38rem">至</div>
    <div class="uploadBtn">
      <el-date-picker
        v-model="dateEndTime"
        type="date"
        size="large"
        :disabled-date="disabledDate2"
      />
    </div>
    <!-- <div class="uploadBtn">
            <el-date-picker v-model="timeDate" type="daterange" range-separator="至" start-placeholder="开始时间"
                end-placeholder="结束时间" size="large" />
        </div> -->
    <div class="uploadBtn">
      <el-button size="large" type="primary" @click="search">查询</el-button>
    </div>
    <!-- <div class="uploadBtn">
            <el-button size="large" type="" @click="exportFile">导出</el-button>
        </div> -->
    <div class="uploadBtn">
      <el-button size="large" type="" @click="uploadFile">文件上传</el-button>
    </div>
    <div class="uploadBtn">
      <el-button size="large" type="" @click="filling">手工填报</el-button>
    </div>
  </div>
  <!-- <div class="unit">单位：万吨</div> -->
  <el-table
    :data="getValues"
    :show-header="false"
    border
    :span-method="objectSpanMethod"
    :style="{ maxWidth: wWidth + 'px' }"
    size="small"
  >
    <el-table-column prop="title" label="" fixed="" :width="56" align="center">
      <template #default="scope">
        <span>{{ identifyResultList[scope.$index].title }}</span>
      </template>
    </el-table-column>
    <el-table-column
      v-for="(item, index) in getHeaders"
      :key="index"
      :prop="item"
      :fixed="index == 0"
      :width="index > resultList.length - 4 ? 50 : 44"
      align="center"
    >
      <template #default="scope">
        <span>{{ scope.row[item] || "-" }}</span>
      </template>
    </el-table-column>
  </el-table>
  <!-- <div class="chart">
    <chart-line-bar
      :chartData="chartList"
      xAxisName="date"
      :title="`${typeUnitName}${currentYear}年药剂数据（乙酸）图`"
      :option="option"
      :chartType="chartType"
      :twoYAxis="false"
      :unit="unit"
      :orient="'horizontal'"
    ></chart-line-bar>
  </div> -->
  <!-- <div class="chart">
    <div class="uploadBtn" v-if="localTypeUnit == 1">
      <el-select
        v-model="typeUnit2"
        class="m-2"
        placeholder="请选择上传单位"
        size="large"
        style="width: 160px"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <chart-line-bar
      :chartData="chartListCompale"
      xAxisName="date"
      :title="`水量对比图`"
      :option="option"
      :chartType="chartType2"
      :twoYAxis="false"
      :unit="'吨'"
      ref="assayChart"
      :orient="'horizontal'"
    ></chart-line-bar>
  </div> -->

  <el-dialog v-model="uploadVisible" :title="dialogTitle" width="60%">
    <el-scrollbar class="containRouter">
      <UploadFile
        :type="uploadType"
        viewType="1"
        waterYieldType="2"
        @submitEditEmit="submitEditEmit"
      ></UploadFile>
    </el-scrollbar>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, computed, nextTick, watch } from "vue";
import moment from "moment";
import dataListHttp from "@/https/dataList.js";
import ChartLineBar from "../charts/ChartLineBar.vue";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import UploadFile from "./upload.vue";
const dateStartTime = ref(moment().startOf("month").format("YYYY-MM-DD"));
const dateEndTime = ref(moment().add(-1, "day").format("YYYY-MM-DD"));
const disabledDate1 = ref((time) => {
  return time.getTime() > Date.now();
});
const disabledDate2 = ref((time) => {
  return (
    time.getTime() < moment(dateStartTime.value) || time.getTime() > Date.now()
  );
});
// const timeDate = ref([moment().startOf('month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')])
const currentYear = ref(moment().format("YYYY"));
const localTypeUnit = ref(Storage.localGet("depId"));
const typeUnit = ref(Storage.localGet("depId"));
const typeUnit2 = ref("2");
watch(typeUnit2, () => {
  chartListCompaleFn();
});
const options = ref([
  // { label: '全部', value: '1' },
  { label: "星沙厂", value: "2" },
  { label: "城西厂", value: "3" },
  { label: "城北厂", value: "4" },
  { label: "城南厂", value: "5" },
]);
const typeUnitName = ref("");
typeUnitName.value =
  typeUnit.value == "1"
    ? "四厂"
    : typeUnit.value == "2"
    ? "星沙厂"
    : typeUnit.value == "3"
    ? "城西厂"
    : typeUnit.value == "4"
    ? "城北厂"
    : "城南厂";
const hHeight = ref(0);
const wWidth = ref(0);
const tableItemWidth = ref(0);
const option = ref({});
const chartType = ref([]);
const uploadVisible = ref(false);
const uploadType = ref("1");
const dialogTitle = ref("");
const chartType2 = ref([]);
const uploadDataList = ref([]);
const uploadInitDataList = ref([]);
if (typeUnit.value == 1) {
  chartType.value = [
    {
      type: "line",
      code: "xingshaCh3cooNa",
      name: "星沙厂",
      linerColor: ["#e33dff", "#e33dff"],
    },
    {
      type: "line",
      code: "cityNorthCh3cooNa",
      name: "城北厂",
      linerColor: ["#ffc550", "#ffc550"],
    },
    {
      type: "line",
      code: "citySouthCh3cooNa",
      name: "城南厂",
      linerColor: ["#b2e3e8", "#b2e3e8"],
    },
    {
      type: "line",
      code: "cityWestCh3cooNa",
      name: "城西厂",
      linerColor: ["#85cc18", "#85cc18"],
    },
  ];
} else if (typeUnit.value == 2) {
  chartType.value = [
    {
      type: "line",
      code: "xingshaCh3cooNa",
      name: "星沙厂",
      linerColor: ["#e33dff", "#e33dff"],
    },
  ];
} else if (typeUnit.value == 3) {
  chartType.value = [
    {
      type: "line",
      code: "cityWestCh3cooNa",
      name: "城西厂",
      linerColor: ["#e33dff", "#e33dff"],
    },
  ];
} else if (typeUnit.value == 4) {
  chartType.value = [
    {
      type: "line",
      code: "cityNorthCh3cooNa",
      name: "城北厂",
      linerColor: ["#e33dff", "#e33dff"],
    },
  ];
} else if (typeUnit.value == 5) {
  chartType.value = [
    {
      type: "line",
      code: "citySouthCh3cooNa",
      name: "城南厂",
      linerColor: ["#e33dff", "#e33dff"],
    },
  ];
}
const unit = ref(["单位:kwh/吨"]);
const chartList = ref([]);
const submitEditEmit = () => {
  uploadVisible.value = false;
  initTable();
  chartListCompaleFn();
};
onMounted(() => {
  // nextTick(() => {
  hHeight.value = document.documentElement.clientHeight - 350;
  wWidth.value = document.documentElement.clientWidth - 270;
  // })
  initTable();
  chartListCompaleFn();
});
const initDate = ref([]);
const chartListCompale = ref([]);
const initTable = () => {
  initDate.value = [];
  resultList.value = [];
  // 计算选中日期相隔天数
  let startTime = moment(dateStartTime.value);
  let endTime = moment(dateEndTime.value);
  let tableDay = endTime.diff(startTime, "day");
  if (tableDay <= 31) {
    tableItemWidth.value = wWidth.value / (tableDay + 7);
  } else {
    tableItemWidth.value = wWidth.value / 38;
  }
  console.log(tableItemWidth.value);
  for (let i = 0; i <= tableDay; i++) {
    initDate.value.push(
      moment(dateStartTime.value).add(i, "day").format("MM-DD")
    );
    if (typeUnit.value == 1) {
      resultList.value.push({
        date: moment(dateStartTime.value).add(i, "day").format("MM-DD"),
        xingshaCh3cooNa: "-",
        citySouthCh3cooNa: "-",
        cityNorthCh3cooNa: "-",
        cityWestCh3cooNa: "-",
        xingshaNa2C2O4: "-",
        citySouthNa2C2O4: "-",
        cityNorthNa2C2O4: "-",
        cityWestNa2C2O4: "-",
        xingshaPac: "-",
        citySouthPac: "-",
        cityNorthPac: "-",
        cityWestPac: "-",
      });
    }
    if (typeUnit.value == 2) {
      resultList.value.push({
        date: moment(dateStartTime.value).add(i, "day").format("MM-DD"),
        xingshaCh3cooNa: "-",
        xingshaNa2C2O4: "-",
        xingshaPac: "-",
      });
    }
    if (typeUnit.value == 3) {
      resultList.value.push({
        date: moment(dateStartTime.value).add(i, "day").format("MM-DD"),
        cityWestCh3cooNa: "-",
        cityWestNa2C2O4: "-",
        cityWestPac: "-",
      });
    }
    if (typeUnit.value == 4) {
      resultList.value.push({
        date: moment(dateStartTime.value).add(i, "day").format("MM-DD"),
        cityNorthCh3cooNa: "-",
        cityNorthNa2C2O4: "-",
        cityNorthPac: "-",
      });
    }
    if (typeUnit.value == 5) {
      resultList.value.push({
        date: moment(dateStartTime.value).add(i, "day").format("MM-DD"),
        citySouthCh3cooNa: "-",
        citySouthNa2C2O4: "-",
        citySouthPac: "-",
      });
    }
  }
  getWaterDateList();
};
const getWaterDateList = () => {
  let params = {
    depId: typeUnit.value,
    startTime: moment(dateStartTime.value).format("YYYY-MM-DD 00:00:00"),
    endTime: moment(dateEndTime.value).format("YYYY-MM-DD 23:59:59"),
  };
  dataListHttp.queryDrug(params).then((res) => {
    console.log(res);
    for (let key in res.data.data) {
      if (initDate.value.includes(key)) {
        let idx = initDate.value.findIndex((item) => {
          return item === key;
        });
        resultList.value[idx] = res.data.data[key];
      }
    }
    uploadDataList.value = JSON.parse(JSON.stringify(resultList.value));
    uploadInitDataList.value = JSON.parse(JSON.stringify(resultList.value));
    chartList.value = uploadInitDataList.value;
    getWaterOtherDateList();
  });
};
const getWaterOtherDateList = () => {
  let params = {
    depId: typeUnit.value,
    startTime: moment(dateStartTime.value).format("YYYY-MM-DD 00:00:00"),
    endTime: moment(dateEndTime.value).format("YYYY-MM-DD 23:59:59"),
  };
  dataListHttp.queryDrugCalculate(params).then((res) => {
    console.log(res);
    for (let key in res.data.data) {
      if (key == "avg") {
        res.data.data[key].date = "平均值";
      }
      if (key == "max") {
        res.data.data[key].date = "最大值";
      }
      if (key == "min") {
        res.data.data[key].date = "最小值";
      }
      if (key == "total") {
        res.data.data[key].date = "累计值";
      }
      if (key == "avg" || key == "max" || key == "min" || key == "total") {
        resultList.value.push(res.data.data[key]);
      }
    }
  });
};
const identifyResultList = ref([]);
if (typeUnit.value == 1) {
  identifyResultList.value = [
    { title: "分类", label: "fl" },
    { title: "乙酸钠(吨)", label: "xingshaCh3cooNa" },
    { title: "乙酸钠", label: "citySouthCh3cooNa" },
    { title: "乙酸钠", label: "cityNorthCh3cooNa" },
    { title: "乙酸钠", label: "cityWestCh3cooNa" },
    { title: "复合碳源(吨)", label: "xingshaNa2C2O4" },
    { title: "复合碳源", label: "citySouthNa2C2O4" },
    { title: "复合碳源", label: "cityNorthNa2C2O4" },
    { title: "复合碳源", label: "cityWestNa2C2O4" },
    { title: "PAC(吨)", label: "xingshaPac" },
    { title: "PAC", label: "citySouthPac" },
    { title: "PAC", label: "cityNorthPac" },
    { title: "PAC", label: "cityWestPac" },
  ];
} else if (typeUnit.value == 2) {
  identifyResultList.value = [
    { title: "分类", label: "fl" },
    { title: "乙酸钠(吨)", label: "xingshaCh3cooNa" },
    { title: "复合碳源(吨)", label: "xingshaNa2C2O4" },
    { title: "PAC(吨)", label: "xingshaPac" },
  ];
} else if (typeUnit.value == 3) {
  identifyResultList.value = [
    { title: "分类", label: "fl" },
    { title: "乙酸钠(吨)", label: "cityWestCh3cooNa" },
    { title: "复合碳源(吨)", label: "cityWestNa2C2O4" },
    { title: "PAC(吨)", label: "cityWestPac" },
  ];
} else if (typeUnit.value == 4) {
  identifyResultList.value = [
    { title: "分类", label: "fl" },
    { title: "乙酸钠(吨)", label: "cityNorthCh3cooNa" },
    { title: "复合碳源(吨)", label: "cityNorthWaterContent" },
    { title: "PAC(吨)", label: "cityNorthPac" },
  ];
} else if (typeUnit.value == 5) {
  identifyResultList.value = [
    { title: "分类", label: "fl" },
    { title: "乙酸钠(吨)", label: "citySouthCh3cooNa" },
    { title: "复合碳源(吨)", label: "citySouthWaterContent" },
    { title: "PAC(吨)", label: "citySouthPac" },
  ];
}
const resultList = ref([]);
const headersList = ref([]);
if (typeUnit.value == 1) {
  headersList.value = [
    {
      prop: "date",
      label: "日期",
    },
    {
      prop: "xingshaCh3cooNa",
      label: "星沙",
    },
    {
      prop: "citySouthCh3cooNa",
      label: "城南",
    },
    {
      prop: "cityNorthCh3cooNa",
      label: "城北",
    },
    {
      prop: "cityWestCh3cooNa",
      label: "城西",
    },
    {
      prop: "xingshaNa2C2O4",
      label: "星沙",
    },
    {
      prop: "citySouthNa2C2O4",
      label: "城南",
    },
    {
      prop: "cityNorthNa2C2O4",
      label: "城北",
    },
    {
      prop: "cityWestNa2C2O4",
      label: "城西",
    },
    {
      prop: "xingshaPac",
      label: "星沙",
    },
    {
      prop: "citySouthPac",
      label: "城南",
    },
    {
      prop: "cityNorthPac",
      label: "城北",
    },
    {
      prop: "cityWestPac",
      label: "城西",
    },
  ];
} else if (typeUnit.value == 2) {
  headersList.value = [
    {
      prop: "date",
      label: "日期",
    },
    {
      prop: "xingshaCh3cooNa",
      label: "星沙",
    },
    {
      prop: "xingshaNa2C2O4",
      label: "星沙",
    },
    {
      prop: "xingshaPac",
      label: "星沙",
    },
  ];
} else if (typeUnit.value == 3) {
  headersList.value = [
    {
      prop: "date",
      label: "日期",
    },
    {
      prop: "cityWestCh3cooNa",
      label: "城西",
    },
    {
      prop: "cityWestNa2C2O4",
      label: "城西",
    },
    {
      prop: "cityWestPac",
      label: "城西",
    },
  ];
} else if (typeUnit.value == 4) {
  headersList.value = [
    {
      prop: "date",
      label: "日期",
    },
    {
      prop: "cityNorthCh3cooNa",
      label: "城北",
    },
    {
      prop: "cityNorthNa2C2O4",
      label: "城北",
    },
    {
      prop: "cityNorthPac",
      label: "城北",
    },
  ];
} else if (typeUnit.value == 5) {
  headersList.value = [
    {
      prop: "date",
      label: "日期",
    },
    {
      prop: "citySouthCh3cooNa",
      label: "城南",
    },
    {
      prop: "citySouthNa2C2O4",
      label: "城南",
    },
    {
      prop: "citySouthPac",
      label: "城南",
    },
  ];
}
const getHeaders = computed(() => {
  return resultList.value.reduce(
    (pre, cur, index) => pre.concat(`value${index}`),
    ["title"]
  );
});
const getValues = computed(() => {
  return headersList.value.map((item) => {
    return resultList.value.reduce(
      (pre, cur, index) =>
        Object.assign(pre, { ["value" + index]: cur[item.prop] }),
      { title: item.label }
    );
  });
});
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (typeUnit.value == 1) {
    if (columnIndex === 0) {
      if (rowIndex === 0) {
        return {
          rowspan: 1,
          colspan: 1,
        };
      } else if (rowIndex === 1) {
        return {
          rowspan: 4,
          colspan: 1,
        };
      } else if (rowIndex === 5) {
        return {
          rowspan: 4,
          colspan: 1,
        };
      } else if (rowIndex === 9) {
        return {
          rowspan: 4,
          colspan: 1,
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }
  }
};
const search = () => {
  initTable();
  chartListCompaleFn();
};
const uploadFile = () => {
  uploadVisible.value = true;
  dialogTitle.value = "上传文件";
  uploadType.value = "1";
};
const filling = () => {
  uploadVisible.value = true;
  dialogTitle.value = "手工填报";
  uploadType.value = "2";
};
const chartListCompaleFn = () => {
  dataListHttp.queryWaterOfLastYear(typeUnit2.value).then((res) => {
    let keys = Object.keys(res.data.data);
    console.log("-------", keys);
    chartType2.value = [
      {
        type: "line",
        code: "last",
        name: "去年",
        linerColor: ["#76da91", "#76da91"],
      },
      {
        type: "line",
        code: "now",
        name: "今年",
        linerColor: ["#63b2ee", "#63b2ee"],
      },
    ];
    let arr = [];
    for (let item in res.data.data[keys[0]]) {
      let month = item.substring(4, 6);
      console.log(month);
      arr.push({
        date: month + "月",
        last: res.data.data[keys[0]][keys[0] + month],
        now: res.data.data[keys[1]][keys[1] + month],
      });
    }
    console.log("===============", arr);
    chartListCompale.value = arr;
  });
};
const exportFile = () => {
  let params = {
    // "depId": 4,
    depId: typeUnit.value,
    startTime: moment(dateStartTime.value).format("YYYY-MM-DD 00:00:00"),
    endTime: moment(dateEndTime.value).format("YYYY-MM-DD 23:59:59"),
  };
  dataListHttp.exportAssay(params).then((response) => {
    console.log(response);
    const content = response.data;
    const blob = new Blob([content], { type: "application/ms-excel" });
    let fileName = `生产数据.xls`;
    if ("download" in document.createElement("a")) {
      // 非IE下载
      const elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName);
    }
  });
};
</script>

<style>
.el-table .el-table__cell {
  max-width: 60px !important;
}

.el-table--small .cell {
  padding: 0 4px !important;
  /* max-width: 60px !important; */
}
</style>
<style scoped lang="less">
.waterYield {
  background: #fff;
  height: 100%;
}

.filter {
  display: flex;
  align-items: center;
}

.uploadBtn {
  text-align: left;
  margin-bottom: 40rem;
  margin-right: 20rem;
}

.chart {
  margin-top: 60px;
}

.unit {
  text-align: right;
  font-size: 14px;
  line-height: 2;
  padding-right: 40px;
  margin-top: -20px;
}
</style>
